package com.bieber.democamp.sharesession.session.redis;

import com.bieber.democamp.sharesession.session.AbstractSessionManager;
import com.bieber.democamp.sharesession.session.Session;
import com.bieber.democamp.util.ObjectUtils;
import com.bieber.democamp.util.RedisClient;
import com.bieber.democamp.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by bieber on 2015/3/16.
 */
public class RedisSessionManager extends AbstractSessionManager {
    @Override
    public Session getSession(HttpServletRequest request, boolean create) throws IOException {
        String sessionId = getSessionIdFromCookie(request);
        if(create){
            if(!StringUtils.isEmpty(sessionId)){
                RedisClient.removeCache(ObjectUtils.object2Bytes(sessionId));
            }
            return new RedisSession(generateSessionId(),getSessionExpire(request));
        }else if(!StringUtils.isEmpty(sessionId)){
            if(RedisClient.exist(ObjectUtils.object2Bytes(sessionId))){
                RedisSession session = new RedisSession(sessionId,getSessionExpire(request));
                return session;
            }
            return null;
        }
        return null;
    }
}
